<template>
  <div class="orders-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #409eff">
              <el-icon size="28"><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.totalOrders || 0 }}</div>
              <div class="stat-label">总订单数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #67c23a">
              <el-icon size="28"><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ statistics.totalAmount || '0.00' }}</div>
              <div class="stat-label">总金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #e6a23c">
              <el-icon size="28"><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.todayOrders || 0 }}</div>
              <div class="stat-label">今日订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #f56c6c">
              <el-icon size="28"><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ statistics.averageAmount || '0.00' }}</div>
              <div class="stat-label">平均订单金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单列表 -->
    <el-card shadow="hover" class="table-card">
      <template #header>
        <div class="card-header">
          <span class="title">订单管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="loadData" :loading="loading">
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选栏 -->
      <div class="filter-bar">
        <el-form :inline="true" :model="queryParams" class="filter-form">
          <el-form-item label="订单状态">
            <el-select v-model="queryParams.status" placeholder="全部状态" clearable style="width: 140px">
              <el-option label="待支付" value="pending" />
              <el-option label="已支付" value="paid" />
              <el-option label="备货中" value="preparing" />
              <el-option label="配送中" value="shipping" />
              <el-option label="已完成" value="delivered" />
              <el-option label="已取消" value="cancelled" />
              <el-option label="已退款" value="refunded" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 260px"
            />
          </el-form-item>

          <el-form-item label="搜索">
            <el-input
              v-model="queryParams.keyword"
              placeholder="订单号/用户/商家"
              clearable
              style="width: 200px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon> 搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><RefreshLeft /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 订单表格 -->
      <el-table
        :data="orderList"
        v-loading="loading"
        style="width: 100%"
        stripe
        border
      >
        <el-table-column prop="orderNo" label="订单号" width="180" fixed />
        <el-table-column prop="username" label="用户" width="120" />
        <el-table-column prop="merchantName" label="商家" width="150" />
        <el-table-column label="订单金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount">¥{{ row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryName" label="收货人" width="100" />
        <el-table-column prop="deliveryPhone" label="联系电话" width="130" />
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleView(row)"
            >
              <el-icon><View /></el-icon> 详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              link
              @click="handleEditStatus(row)"
            >
              <el-icon><Edit /></el-icon> 状态
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(row)"
              :disabled="!canDelete(row.status)"
            >
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-loading="detailLoading" class="order-detail">
        <el-descriptions :column="2" border v-if="currentOrder">
          <el-descriptions-item label="订单号" :span="2">
            <el-tag>{{ currentOrder.orderNo }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户">
            {{ currentOrder.username }}
          </el-descriptions-item>
          <el-descriptions-item label="商家" :span="2">
            {{ currentOrder.merchantName }}
          </el-descriptions-item>
          <el-descriptions-item label="收货人">
            {{ currentOrder.deliveryName }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ currentOrder.deliveryPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">
            {{ currentOrder.deliveryAddress }}
          </el-descriptions-item>
          <el-descriptions-item label="商品金额">
            ¥{{ currentOrder.foodAmount }}
          </el-descriptions-item>
          <el-descriptions-item label="配送费">
            ¥{{ currentOrder.deliveryFee }}
          </el-descriptions-item>
          <el-descriptions-item label="订单总额">
            <span class="total-amount">¥{{ currentOrder.totalAmount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="预约时间">
            {{ currentOrder.scheduledDeliveryDate }} {{ currentOrder.scheduledDeliveryTime }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ currentOrder.notes || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDateTime(currentOrder.createdAt) }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 订单商品列表 -->
        <div class="order-items" v-if="currentOrder && currentOrder.items">
          <h4>订单商品</h4>
          <el-table :data="currentOrder.items" border>
            <el-table-column prop="foodName" label="商品名称" />
            <el-table-column prop="foodPrice" label="单价" width="100" align="right">
              <template #default="{ row }">¥{{ row.foodPrice }}</template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" align="center" />
            <el-table-column prop="spiceLevel" label="辣度" width="100" align="center" />
            <el-table-column prop="subtotal" label="小计" width="100" align="right">
              <template #default="{ row }">¥{{ row.subtotal }}</template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 修改状态对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="修改订单状态"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(statusForm.currentStatus)">
            {{ getStatusText(statusForm.currentStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态" required>
          <el-select v-model="statusForm.newStatus" placeholder="请选择新状态" style="width: 100%">
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="备货中" value="preparing" />
            <el-option label="配送中" value="shipping" />
            <el-option label="已完成" value="delivered" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item label="修改原因" required>
          <el-input
            v-model="statusForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入修改原因（必填）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmUpdateStatus"
          :loading="statusLoading"
          :disabled="!statusForm.newStatus || !statusForm.reason"
        >
          确定修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document,
  Money,
  Clock,
  TrendCharts,
  Refresh,
  Search,
  RefreshLeft,
  View,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { getOrderList, getOrderDetail, deleteOrder, updateOrderStatus, getOrderStatistics } from '@/api/orders'

// 数据
const loading = ref(false)
const detailLoading = ref(false)
const statusLoading = ref(false)
const orderList = ref([])
const total = ref(0)
const statistics = ref({})
const dateRange = ref([])

// 查询参数
const queryParams = reactive({
  page: 1,
  size: 20,
  status: '',
  keyword: '',
  startDate: '',
  endDate: '',
  sortBy: 'createdAt',
  sortOrder: 'desc'
})

// 对话框
const detailDialogVisible = ref(false)
const statusDialogVisible = ref(false)
const currentOrder = ref(null)

// 状态表单
const statusForm = reactive({
  orderId: null,
  currentStatus: '',
  newStatus: '',
  reason: ''
})

// 监听日期范围变化
watch(dateRange, (newVal) => {
  if (newVal && newVal.length === 2) {
    queryParams.startDate = newVal[0]
    queryParams.endDate = newVal[1]
  } else {
    queryParams.startDate = ''
    queryParams.endDate = ''
  }
})

// 生命周期
onMounted(() => {
  loadData()
  loadStatistics()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getOrderList(queryParams)
    orderList.value = res.data.items || []
    total.value = res.data.total || 0
  } catch (error) {
    console.error('加载订单列表失败:', error)
    ElMessage.error(error.message || '加载失败')
  } finally {
    loading.value = false
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const res = await getOrderStatistics()
    statistics.value = res.data || {}
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(queryParams, {
    page: 1,
    size: 20,
    status: '',
    keyword: '',
    startDate: '',
    endDate: ''
  })
  dateRange.value = []
  loadData()
}

// 分页变化
const handlePageChange = (page) => {
  queryParams.page = page
  loadData()
}

const handleSizeChange = (size) => {
  queryParams.size = size
  queryParams.page = 1
  loadData()
}

// 查看详情
const handleView = async (row) => {
  detailDialogVisible.value = true
  detailLoading.value = true
  try {
    const res = await getOrderDetail(row.id)
    currentOrder.value = res.data
  } catch (error) {
    console.error('加载订单详情失败:', error)
    ElMessage.error(error.message || '加载失败')
  } finally {
    detailLoading.value = false
  }
}

// 修改状态
const handleEditStatus = (row) => {
  statusForm.orderId = row.id
  statusForm.currentStatus = row.status
  statusForm.newStatus = ''
  statusForm.reason = ''
  statusDialogVisible.value = true
}

// 确认修改状态
const confirmUpdateStatus = async () => {
  if (!statusForm.newStatus) {
    ElMessage.warning('请选择新状态')
    return
  }
  if (!statusForm.reason.trim()) {
    ElMessage.warning('请输入修改原因')
    return
  }

  statusLoading.value = true
  try {
    await updateOrderStatus(statusForm.orderId, {
      status: statusForm.newStatus,
      reason: statusForm.reason
    })
    ElMessage.success('状态修改成功')
    statusDialogVisible.value = false
    loadData()
    loadStatistics()
  } catch (error) {
    console.error('修改状态失败:', error)
    ElMessage.error(error.message || '修改失败')
  } finally {
    statusLoading.value = false
  }
}

// 删除订单
const handleDelete = (row) => {
  if (!canDelete(row.status)) {
    ElMessage.warning('只能删除已取消或已退款的订单')
    return
  }

  ElMessageBox.confirm(
    `确定要删除订单 ${row.orderNo} 吗？此操作不可恢复！`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    }
  ).then(async () => {
    try {
      await deleteOrder(row.id)
      ElMessage.success('删除成功')
      loadData()
      loadStatistics()
    } catch (error) {
      console.error('删除订单失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 工具函数
const canDelete = (status) => {
  return status === 'cancelled' || status === 'refunded'
}

const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    paid: 'success',
    preparing: 'primary',
    shipping: '',
    delivered: 'success',
    cancelled: 'info',
    refunded: 'danger'
  }
  return types[status] || ''
}

const getStatusText = (status) => {
  const texts = {
    pending: '待支付',
    paid: '已支付',
    preparing: '备货中',
    shipping: '配送中',
    delivered: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return texts[status] || status
}

const formatDateTime = (datetime) => {
  if (!datetime) return '-'
  const date = new Date(datetime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-')
}
</script>

<style scoped>
.orders-container {
  padding: 20px;
}

/* 统计卡片 */
.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 表格卡片 */
.table-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

/* 筛选栏 */
.filter-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.filter-form {
  margin: 0;
}

/* 金额显示 */
.amount {
  color: #f56c6c;
  font-weight: bold;
}

.total-amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

/* 分页 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 订单详情 */
.order-detail {
  min-height: 200px;
}

.order-items {
  margin-top: 20px;
}

.order-items h4 {
  margin-bottom: 10px;
  color: #303133;
}

/* 响应式 */
@media (max-width: 768px) {
  .filter-form {
    display: block;
  }
  
  .filter-form :deep(.el-form-item) {
    display: block;
    margin-right: 0;
  }
}
</style>


